<template>
  <div class="energyUnitprice">
    <lb-layout
      v-loading="$store.getters.loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="#a19f9fb0;"
      :paddBottom="5"
      :needfixBtn="false"
    >
      <!-- 查询 or 新增 or 修改-->
      <el-row>
        <el-col :span="21">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
          >
            <el-form-item
              label="电费电价版本号:"
              v-show="showSearch"
              prop="version"
            >
              <el-select
                size="small"
                v-model="queryParams.versionid"
                placeholder="请选择"
                :disabled="!editFlage"
                @change="handleSelectver"
                @visible-change="chekVersionsArr"
                v-hasPermi="['energy:manage:list']"
              >
                <el-option
                  v-for="(item, index) in versionsArr"
                  :key="index"
                  :label="item.version"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-show="!showSearch"
              :rules="addRules.versionName"
              prop="versionName"
            >
              <!-- <el-input
                size="small"
                v-model="queryParams.versionName"
                placeholder="电费电价版本号"
                clearable
              ></el-input> -->
              <div>
                <span>版本号 </span>
                <span v-if="queryParams.versionName" class="versionName-span">
                  {{ queryParams.versionName }}
                </span>
                <span v-else class="versionName-span2">将自动生成</span>
              </div>
            </el-form-item>
            <el-form-item v-show="addFlage" label="用电类型:" prop="type">
              <el-select
                size="small"
                v-model="queryParams.type"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in dict.type.electric_energy_type"
                  :key="index"
                  :label="item.label"
                  :value="Number(item.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleQuery(0)"
                v-show="addFlage && editFlage"
                v-hasPermi="['energy:manage:list']"
              >
                搜索
              </el-button>
              <el-button
                icon="el-icon-refresh"
                size="small"
                @click="handleresetQuery"
                v-show="addFlage && editFlage"
                v-hasPermi="['energy:manage:list']"
              >
                重置
              </el-button>
              <el-button
                :icon="editFlage ? 'el-icon-edit' : 'el-icon-check'"
                size="small"
                :type="editFlage ? 'primary' : 'success'"
                :disabled="!addFlage"
                v-show="addFlage && publishStatus"
                @click="handleEdit"
                v-hasPermi="['energy:manage:edit']"
              >
                {{ editFlage ? "编辑" : "保存" }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="3" class="button-area-ex">
          <el-button
            type="primary"
            size="small"
            :plain="addFlage"
            icon="el-icon-plus"
            :disabled="!editFlage"
            v-show="editFlage"
            @click="handleAdd"
            v-hasPermi="['energy:manage:edit']"
          >
            {{ addFlage ? "新增版本" : "确认" }}
          </el-button>
          <el-button
            type="primary"
            v-show="!addFlage || !editFlage"
            plain
            size="small"
            @click="handleCancel"
          >
            取消
          </el-button>
          <el-button
            type="success"
            v-show="publishStatus && addFlage && editFlage"
            size="small"
            icon="el-icon-upload2"
            @click="handlePublish"
            v-hasPermi="['energy:manage:audit']"
          >
            发布
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格标题 -->
      <el-row>
        <el-col :span="12" :offset="6">
          <ex-footer>
            <div slot="title">
              <span style="font-size: 18px">
                浙江省舟山市机关事务工作用电单价（元/千瓦时）
              </span>
            </div>
          </ex-footer>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-row>
        <el-col :span="24">
          <el-form
            :model="listform"
            ref="tableForm"
            :rules="listRules"
            size="small"
          >
            <el-table
              :data="listform.list"
              border
              :height="!addFlage || !editFlage ? 370 : 400"
            >
              <el-table-column
                prop="type"
                label="用电类型"
                align="center"
                show-overflow-tooltip
                width="200px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.type'"
                    :rules="listRules.type"
                    class="cellCenter"
                    v-show="!inputFlage"
                  >
                    <el-select
                      size="small"
                      v-model="scope.row.type"
                      :disabled="inputFlage"
                    >
                      <el-option
                        v-for="(item, index) in dict.type.electric_energy_type"
                        :key="index"
                        :label="item.label"
                        :value="Number(item.value)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <dict-tag
                    v-show="inputFlage"
                    :options="dict.type.electric_energy_type"
                    :value="scope.row.type + ''"
                  />
                </template>
              </el-table-column>
              <!-- show-summary 合计 -->
              <el-table-column
                prop="level"
                label="电压等级"
                align="center"
                min-width="120"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.level'"
                    :rules="listRules.level"
                    class="cellCenter"
                    v-show="!inputFlage"
                  >
                    <el-select
                      size="small"
                      v-model="scope.row.level"
                      :disabled="inputFlage"
                    >
                      <el-option
                        v-for="(item, index) in dict.type.voltage_level_type"
                        :key="index"
                        :label="item.label"
                        :value="Number(item.value)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <dict-tag
                    v-show="inputFlage"
                    :options="dict.type.voltage_level_type"
                    :value="scope.row.level + ''"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="elPrice" label="电度电价" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.elPrice'"
                    :rules="listRules.elPrice"
                    class="cellCenter"
                    v-show="!inputFlage"
                  >
                    <el-input
                      size="small"
                      type="number"
                      v-model.number="scope.row.elPrice"
                      :readonly="inputFlage"
                    ></el-input>
                  </el-form-item>
                  <span v-show="inputFlage">{{ scope.row.elPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column label="电压等级子级" align="center">
                <template slot="header">
                  <div class="flexex">
                    <div>电压等级子级</div>
                    <el-popover
                      placement="top-start"
                      title="电压等级子级"
                      trigger="hover"
                    >
                      <p>单位：年累计用电量kwh</p>
                      <i slot="reference" class="el-icon-info"></i>
                    </el-popover>
                  </div>
                </template>
                <el-table-column
                  prop="powerRangeStart"
                  label="起始"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.powerRangeStart'"
                      :rules="listRules.powerRangeStart"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.powerRangeStart"
                        :readonly="inputFlage"
                        @input="
                          checknum(
                            scope.row.powerRangeStart,
                            scope.$index,
                            'powerRangeStart'
                          )
                        "
                        @blur="
                          checknum2(
                            scope.row.powerRangeStart,
                            scope.$index,
                            'powerRangeStart'
                          )
                        "
                      ></el-input>
                    </el-form-item>
                    <span v-show="inputFlage">
                      {{ scope.row.powerRangeStart }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="powerRangeEnd"
                  label="结束"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.powerRangeEnd'"
                      :rules="listRules.powerRangeEnd"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.powerRangeEnd"
                        :readonly="inputFlage"
                        @input="
                          checknum(
                            scope.row.powerRangeEnd,
                            scope.$index,
                            'powerRangeEnd'
                          )
                        "
                        @blur="
                          checknum2(
                            scope.row.powerRangeEnd,
                            scope.$index,
                            'powerRangeEnd'
                          )
                        "
                      ></el-input>
                    </el-form-item>
                    <span v-show="inputFlage">
                      {{ scope.row.powerRangeEnd }}
                    </span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="分时段电价" align="center">
                <el-table-column
                  prop="peakPrice"
                  label="尖峰"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.peakPrice'"
                      :rules="listRules.peakPrice"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.peakPrice"
                        :readonly="inputFlage"
                        @input="
                          (val) => {
                            toInteger(val, 4, scope.$index, 'peakPrice');
                          }
                        "
                      ></el-input>
                    </el-form-item>
                    <span v-show="inputFlage">{{ scope.row.peakPrice }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="highPrice"
                  label="高峰"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.highPrice'"
                      :rules="listRules.highPrice"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.highPrice"
                        :readonly="inputFlage"
                        @input="
                          (val) => {
                            replaceDigitDeal(val, 4, scope.$index, 'highPrice');
                          }
                        "
                      ></el-input>
                    </el-form-item>
                    <span v-show="inputFlage">{{ scope.row.highPrice }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="lowPrice"
                  label="低谷"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.lowPrice'"
                      :rules="listRules.lowPrice"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.lowPrice"
                        :readonly="inputFlage"
                        @input="
                          (val) => {
                            toInteger(val, 4, scope.$index, 'lowPrice');
                          }
                        "
                      ></el-input>
                    </el-form-item>
                    <span v-show="inputFlage">{{ scope.row.lowPrice }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="diffPrice"
                  label="峰谷差价"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input
                      size="small"
                      v-show="!inputFlage"
                      v-model="scope.row.diffPrice"
                      disabled
                    ></el-input>
                    <span v-show="inputFlage">{{ scope.row.diffPrice }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="基本电价" align="center">
                <template slot="header">
                  <div class="flexex">
                    <div>基本电价</div>
                    <el-popover
                      placement="top-start"
                      title="基本电价"
                      trigger="hover"
                    >
                      <p>单位：元/千瓦月</p>
                      <i slot="reference" class="el-icon-info"></i>
                    </el-popover>
                  </div>
                </template>
                <el-table-column
                  prop="maxDemand"
                  label="最大需量"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.maxDemand'"
                      :rules="listRules.maxDemand"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.maxDemand"
                        :readonly="inputFlage"
                      >
                      </el-input>
                    </el-form-item>
                    <span v-show="inputFlage">{{ scope.row.maxDemand }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transformerCapacity"
                  label="变压器容量"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.transformerCapacity'"
                      :rules="listRules.transformerCapacity"
                      class="cellCenter"
                      v-show="!inputFlage"
                    >
                      <el-input
                        size="small"
                        type="number"
                        v-model.number="scope.row.transformerCapacity"
                        :readonly="inputFlage"
                      >
                      </el-input>
                    </el-form-item>
                    <span v-show="inputFlage">
                      {{ scope.row.transformerCapacity }}
                    </span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="100"
                v-if="!inputFlage"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="text"
                    icon="el-icon-delete"
                    class="text-danger"
                    @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>
      </el-row>
      <!-- 增行按钮 -->
      <el-row v-show="!addFlage || !editFlage" style="margin-top: 20px">
        <el-col :span="8" :offset="8" class="midbutton">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            circle
            @click="addRow"
          ></el-button>
        </el-col>
      </el-row>
      <!-- 网址 电话 文件 -->
      <el-row>
        <el-col :span="24">
          <el-form
            :model="addParams"
            size="small"
            ref="addform"
            :rules="addRules"
          >
            <el-row style="margin-top: 20px" class="midrow">
              <el-col
                :xs="xsObj"
                :sm="smObj"
                :md="mdObj"
                :lg="lgObj"
                :class="['midcol', inputFlage ? 'midcolmini' : '']"
              >
                <el-form-item label="舟山电网网址:" prop="website">
                  <el-input
                    size="small"
                    v-model="addParams.website"
                    style="width: 250px"
                    v-show="!inputFlage"
                  ></el-input>
                  <el-tooltip
                    popper-class="show-tooltip"
                    effect="light"
                    :content="addParams.website"
                    :disabled="addParams.website.length >= 30 ? false : true"
                    placement="top"
                    v-show="inputFlage"
                  >
                    <div class="sapn-input">
                      <span>
                        {{ addParams.website }}
                      </span>
                    </div>
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col
                :xs="xsObj"
                :sm="smObj"
                :md="mdObj"
                :lg="lgObj"
                :class="['midcol', inputFlage ? 'midcolmini' : '']"
              >
                <el-form-item label="舟山电网客服热线电话:" prop="servicePhone">
                  <el-input
                    size="small"
                    v-model="addParams.servicePhone"
                    style="width: 250px"
                    v-show="!inputFlage"
                  ></el-input>
                  <div v-show="inputFlage" class="sapn-input">
                    <span>{{ addParams.servicePhone }}</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="midrow">
              <el-col
                :span="24"
                :class="[
                  'midcol',
                  'inline-col',
                  inputFlage ? 'midcolmini' : '',
                ]"
              >
                <el-form-item label="依据政策文件:" prop="officialFileId">
                  <el-select
                    v-show="!inputFlage"
                    size="small"
                    v-model="addParams.officialFileId"
                    style="width: 250px"
                    @visible-change="handleSelectfile"
                  >
                    <el-option
                      v-for="item in officialFileArr"
                      :key="item.id"
                      :label="item.documentTitle"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                  <el-tooltip
                    popper-class="show-tooltip"
                    effect="light"
                    :content="addParams.officialFile"
                    :disabled="
                      addParams.officialFile.length >= 30 ? false : true
                    "
                    placement="top"
                    v-show="inputFlage"
                  >
                    <div class="sapn-input">
                      <span>{{ addParams.officialFile }}</span>
                    </div>
                  </el-tooltip>
                </el-form-item>
                <el-button
                  @click="preview"
                  icon="el-icon-download"
                  type="text"
                  size="small"
                >
                  文件预览
                </el-button>
              </el-col>
            </el-row>
            <el-row class="midrow" v-show="inputFlage">
              <el-col
                :xs="xsObj"
                :sm="smObj"
                :md="mdObj"
                :lg="lgObj"
                :class="['midcol', inputFlage ? 'midcolmini' : '']"
              >
                <el-form-item label="制定时间:" prop="activeTime">
                  <span>
                    {{ addParams.activeTime }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col
                :xs="xsObj"
                :sm="smObj"
                :md="mdObj"
                :lg="lgObj"
                :class="['midcol', inputFlage ? 'midcolmini' : '']"
              >
                <el-form-item label="失效时间:" prop="inactiveTime">
                  <span>
                    {{ addParams.inactiveTime }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <!-- 底部注释 -->
      <ex-footer
        :data="{
          title: '注释:',
          config: [
            {
              label: '尖峰',
              value: '9:00-11:00，15:00-17:00',
              formatMoney: false,
            },
            {
              label: '高峰',
              value: '8:00-9:00，13:00-15:00，17:00-22:00',
              formatMoney: false,
            },
            {
              label: '低谷',
              value: '11:00-13:00，22:00-次日8:00',
              formatMoney: false,
            },
          ],
        }"
      >
        <div slot="title">
          <span>注释:</span>
        </div>
        <div slot="tail">
          <span>
            夏季7、8月份及冬季1、12月份的13:00-15:00由高峰时段调整为尖峰时段，执行尖峰电价
          </span>
        </div>
      </ex-footer>
    </lb-layout>
  </div>
</template>

<script>
import {
  listPricemanageversion,
  listPricemanage,
  auditPricemanage,
  addPricemanage,
  editPricemanage,
} from "@/api/energyconsumption/unitprice";
import {
  validWeburl,
  validPhoe,
  validMoney,
  validVersions,
  validPositiveInteger,
} from "@/utils/validate.js";
import { getPlatelist } from "@/api/basicdata/uploadManage"; // 获取政策文件集合
import { deepClone, replaceDigit, replaceInteger } from "@/utils/index";
import exFooter from "@/views/configuration/standard/components/ex-footer.vue";
export default {
  name: "energyUnitprice",
  components: {
    exFooter,
  },
  dicts: ["electric_energy_type", "voltage_level_type"],
  data() {
    return {
      xsObj: {
        span: 12,
      },
      smObj: {
        span: 12,
      },
      mdObj: {
        span: 12,
      },
      lgObj: {
        span: 8,
      },
      xlObj: {
        span: 8,
      },
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        versionid: null, // 版本的ID
        type: null, // 用电类型
        versionName: null, // 同queryParams.versionid的version
      },
      // addVersionname: null,
      // 版本号集合
      versionsArr: [],
      // 用电类型
      electricType: [],
      // 电压等级
      voltageLevel: [],
      publishStatus: false,
      // 表格数据
      listform: {
        list: [],
      },
      listRules: {
        // version: [
        //   { required: true, message: "版本号不能为空", trigger: "blur" },
        // ],
        level: [
          { required: true, message: "电压等级不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "用电类型不能为空", trigger: "blur" },
        ],
        elPrice: [
          { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validMoneytest },
        ],
        peakPrice: [
          // { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validMoneytest },
        ],
        highPrice: [
          // { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validMoneytest },
        ],
        lowPrice: [
          // { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validMoneytest },
        ],
        maxDemand: [
          // { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validMoneytest2 },
        ],
        transformerCapacity: [
          // { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validMoneytest2 },
        ],
        powerRangeStart: [
          { validator: this.validPositiveIntegertest, tigger: "blur" },
        ],
        powerRangeEnd: [
          { validator: this.validPositiveIntegertest, tigger: "blur" },
        ],
      },
      indexFlage: 0,
      // 输入框钩子
      inputFlage: true,
      // 编辑钩子
      editFlage: true,
      // 新增版本钩子
      addFlage: true,
      /* ......................数据交互...................... */
      // 新增参数
      addParams: {
        website: "", // 电网地址
        servicePhone: "", // 热线电话
        officialFile: "", // 依据文件
        officialFileId: null, // 依据文件ID
        activeTime: "", // 生效时间
        inactiveTime: "", // 失效时间
      },
      addRules: {
        website: [
          { required: true, message: "网址不能为空", trigger: "blur" },
          { validator: this.validURLtest },
        ],
        servicePhone: [
          { required: true, message: "热线电话不能为空", trigger: "blur" },
          { validator: this.validPhoetest },
        ],
        officialFileId: [
          { required: true, message: "依据政策文件不能为空", trigger: "blur" },
        ],
        // versionName: [
        //   { required: true, message: "版本号不能为空", trigger: "blur" },
        //   { validator: this.validVersionstest },
        // ],
      },
      officialFileArr: [], // 政策文件集合
      // 规格配置单行数据结构
      rowObj: {
        type: null, // 用电类型
        level: null, // 电压等级
        elPrice: null, // 电度电价
        powerRangeStart: null, // 起始
        powerRangeEnd: null, // 结束
        peakPrice: null, // 尖峰电价
        highPrice: null, // 高峰电价
        lowPrice: null, // 低谷电价
        diffPrice: null, // 峰谷差价
        maxDemand: null, // 最大需量
        transformerCapacity: null, // 变压器容量
      },
    };
  },
  created() {
    this.requestPlatelist();
  },
  mounted() {
    this.initializeGet();
  },
  methods: {
    /* 自定义校验 */
    validURLtest(rule, value, callback) {
      if (!validWeburl(value)) {
        callback("网址名称格式不正确");
      } else {
        callback();
      }
    },
    validPhoetest(rule, value, callback) {
      if (!validPhoe(value)) {
        callback("热线电话格式不正确");
      } else {
        callback();
      }
    },
    validMoneytest(rule, value, callback) {
      if (!validMoney(value, 4)) {
        callback("金额格式不正确");
      } else {
        if (value > 99.9999) {
          callback("金额最高为99.9999");
        } else {
          callback();
        }
      }
    },
    validMoneytest2(rule, value, callback) {
      if (!validMoney(value, 4)) {
        callback("金额格式不正确");
      } else {
        if (value > 999999.9999) {
          callback("金额最高为999999.9999");
        } else {
          callback();
        }
      }
    },
    validVersionstest(rule, value, callback) {
      if (!validVersions(value)) {
        callback("版本号只能为11位数字");
      } else {
        callback();
      }
    },
    validPositiveIntegertest(rule, value, callback) {
      let that = this;
      let start, end;
      start = that.listform.list[that.indexFlage].powerRangeStart;
      end = that.listform.list[that.indexFlage].powerRangeEnd;
      console.log(start, end);
      if (start == null && end == null) {
        callback();
      } else if (start != null && end == null) {
        callback();
      } else if (start == null && end != null) {
        callback("请设置起始");
      } else if (start != null && end != null) {
        if (start >= end) {
          callback("起始应小于结束");
        } else {
          callback();
        }
      }
    },
    //! 同用电类型同电压等级下，起始值和结束值代表的范围不能重复
    validNorepeat(list) {
      let classArr = []; // 种类集合
      let comeArr = []; // 相同种类数据集合的集合
      let comeFlage = 0; // 有无电压等级子级重复判断钩子
      let elFlage = 0; // 电度电价重复判断钩子
      let repeatArr = []; // 重复的内容集合
      let elSameArr = []; // 重复电度的内容集合
      let showArr = []; // 提示的用电类型—电压等级集合
      let elShowArr = []; // 提示电度电价的集合
      // 1.确定用电类型和电压等级组合有几种并区分分类集合
      list.map((item) => {
        classArr.push({ type: item.type, level: item.level });
      });
      classArr = deepClone(classArr);
      for (let i = 0; i < classArr.length; i++) {
        for (let j = i + 1; j < classArr.length; j++) {
          if (
            classArr[i].level === classArr[j].level &&
            classArr[i].type === classArr[j].type
          ) {
            classArr.splice(j, 1);
            // classArr.length--;
            // j--;
          }
        }
      }
      console.log(classArr, "组合种类");
      // 2.将相同种类数据放入集合中再放入集合中
      classArr.map((item) => {
        let arr = new Array();
        list.map((tig) => {
          if (item.level === tig.level && item.type === tig.type) {
            let obj = {
              type: tig.type,
              level: tig.level,
              powerRangeStart: tig.powerRangeStart,
              powerRangeEnd: tig.powerRangeEnd,
              elPrice: tig.elPrice,
            };
            arr.push(obj);
          }
        });
        comeArr.push(arr);
      });
      console.log(comeArr, "相同种类数据集合的集合");
      // 3.每种组合的起始和结束有没有重复 判断电度电价是否重复
      comeArr.map((item) => {
        let falge = false; // 子级钩子
        let elsame = false; // 电度钩子
        if (item.length > 1) {
          let num = 0;
          for (let i = 0; i < item.length; i++) {
            for (let j = i + 1; j < item.length; j++) {
              // 电度电价
              if (item[i].elPrice == item[j].elPrice) {
                elsame = true;
              }
              // 起始结束
              if (
                item[i].powerRangeStart == null &&
                item[i].powerRangeEnd == null
              ) {
                if (item.length >= 2) {
                  // falge = true;
                  num++;
                  console.log("情况1-1");
                }
              } else if (
                item[j].powerRangeStart == null &&
                item[j].powerRangeEnd == null
              ) {
                if (item.length >= 2) {
                  // falge = true;
                  num++;
                  console.log("情况1-2");
                }
              } else if (
                item[i].powerRangeStart != null &&
                item[i].powerRangeEnd == null
              ) {
                if (item[j].powerRangeStart != null) {
                  if (item[j].powerRangeEnd == null) {
                    if (item[i].powerRangeStart <= item[j].powerRangeStart) {
                      num++;
                      console.log("情况2-1-1");
                    }
                  } else {
                    if (item[i].powerRangeStart <= item[j].powerRangeEnd) {
                      num++;
                      console.log("情况2-1-2");
                    }
                  }
                } else {
                  num++;
                  console.log("情况2-1-3");
                }
              } else if (
                item[j].powerRangeStart != null &&
                item[j].powerRangeEnd == null
              ) {
                if (item[i].powerRangeStart != null) {
                  if (item[i].powerRangeEnd == null) {
                    if (item[j].powerRangeStart <= item[i].powerRangeStart) {
                      num++;
                      console.log("情况2-2-1");
                    }
                  } else {
                    if (item[j].powerRangeStart <= item[i].powerRangeEnd) {
                      num++;
                      console.log("情况2-2-2");
                    }
                  }
                } else {
                  num++;
                  console.log("情况2-2-3");
                }
              } else {
                console.log("情况3");
                let face =
                  Math.max(item[j].powerRangeStart, item[i].powerRangeStart) <=
                  Math.min(item[j].powerRangeEnd, item[i].powerRangeEnd);
                console.log(
                  face,
                  Math.max(item[j].powerRangeStart, item[i].powerRangeStart),
                  Math.min(item[j].powerRangeEnd, item[i].powerRangeEnd)
                );
                if (face) {
                  num++;
                }
              }
            }
          }
          console.log(num, "num");
          if (num != 0) {
            falge = true;
          }
        } else if (item.length == 1) {
          falge = false;
        }
        if (elsame) {
          elFlage++;
          if (elSameArr.length == 0) {
            elSameArr.push(item);
          } else {
            elSameArr.map((tig) => {
              if (tig.type != item.type || tig.level != item.level) {
                elSameArr.push(item);
              }
            });
          }
        }
        if (falge) {
          comeFlage++;
          if (repeatArr.length == 0) {
            repeatArr.push(item);
          } else {
            repeatArr.map((tig) => {
              if (tig.type != item.type || tig.level != item.level) {
                repeatArr.push(item);
              }
            });
          }
        }
      });
      console.log(repeatArr, "重复的数据的集合");
      // 4.找到重复的地方并提示
      // 电度电价重复
      if (elSameArr.length > 0) {
        elSameArr.map((item) => {
          let nameobj = {};
          this.dict.type.electric_energy_type.map((tig) => {
            if (item[0].type == Number(tig.value)) {
              nameobj.typeName = tig.label;
            }
          });
          this.dict.type.voltage_level_type.map((pig) => {
            if (item[0].level == Number(pig.value)) {
              nameobj.levelName = pig.label;
            }
          });
          elShowArr.push(nameobj);
        });
      }
      // 电压等级子级重复
      if (repeatArr.length > 0) {
        repeatArr.map((item) => {
          let nameobj = {};
          this.dict.type.electric_energy_type.map((tig) => {
            if (item[0].type == Number(tig.value)) {
              nameobj.typeName = tig.label;
            }
          });
          this.dict.type.voltage_level_type.map((pig) => {
            if (item[0].level == Number(pig.value)) {
              nameobj.levelName = pig.label;
            }
          });
          showArr.push(nameobj);
        });
      }
      if (elFlage != 0) {
        let msg = "";
        if (elShowArr.length == 1) {
          msg = elShowArr[0].typeName + "—" + elShowArr[0].levelName;
        } else {
          elShowArr.map((item) => {
            msg += " " + item.typeName + "—" + item.levelName + " ";
          });
        }
        this.$message.error("表格数据" + msg + "的电镀电价有重复");
        return false;
      } else {
        if (comeFlage != 0) {
          let msg = "";
          if (showArr.length == 1) {
            msg = showArr[0].typeName + "—" + showArr[0].levelName;
          } else {
            showArr.map((item) => {
              msg += " " + item.typeName + "—" + item.levelName + " ";
            });
          }
          this.$message.error("表格数据" + msg + "的电压等级子级范围有重复");
          return false;
        } else {
          return true;
        }
      }
    },
    // queryParams获取版本名称
    handleSelectver() {
      let id = this.queryParams.versionid;
      this.versionsArr.map((item) => {
        if (item.id === id) {
          this.queryParams.versionName = item.version;
        }
      });
    },
    /* 远程下拉框请求数据 */
    chekVersionsArr(val) {
      if (val) {
        if (this.versionsArr.length == 0) {
          this.getVersions();
        }
      }
    },
    //todo 初始化请求
    async initializeGet(versionID) {
      const aa = await this.getVersions(versionID);
      const bb = await this.handleQuery(aa);
    },
    // todo 查询版本对应配置列表
    getList() {
      let params = {};
      if (this.queryParams.type != null) {
        params.type = this.queryParams.type;
      } else {
        params.type = null;
      }
      params.id = this.queryParams.versionid;
      this.$store.commit("app/updateApiCount", "add");
      listPricemanage(params)
        .then((res) => {
          console.log(res, "版本对应配置列表");
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.listform.list = res?.data?.energyPriceDetailVoList ?? [];
          if (this.listform.list.length > 0) {
            // 差价计算
            this.listform.list.map((item) => {
              // item.type = JSON.stringify(item.type);
              // item.level = JSON.stringify(item.level);
              item.diffPrice = replaceDigit(
                item?.peakPrice ?? 0 - item?.lowPrice ?? 0,
                4
              );
            });
          }
          // 发布按钮状态
          this.publishStatus = res?.data?.status == 0 ? true : false;
          // 赋予新增参数数据
          this.addParams.website = res?.data?.website ?? "";
          this.addParams.servicePhone = res?.data?.servicePhone ?? "";
          this.addParams.officialFile = res?.data?.officialFile ?? "";
          this.addParams.officialFileId = res?.data?.officialFileId ?? 0;
          this.addParams.activeTime = res?.data?.activeTime ?? "暂无生效时间";
          this.addParams.inactiveTime =
            res?.data?.inactiveTime ?? "暂无失效时间";
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20015");
        });
    },
    // todo 请求版本号的集合
    getVersions(versionID) {
      return new Promise((resolve, reject) => {
        listPricemanageversion()
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            this.versionsArr = res?.data ?? [];
            if (this.versionsArr.length > 0) {
              if (versionID == undefined) {
                this.queryParams.versionid = this.versionsArr[0]?.id ?? 0; // 默认请求第一个版本
                this.queryParams.versionName =
                  this.versionsArr[0]?.version ?? "";
                resolve(true);
              } else {
                if (versionID == "add") {
                  // 新增
                  // this.versionsArr.map((item) => {
                  //   if (item.version == this.addVersionname) {
                  //     this.queryParams.versionid = item.id;
                  //     this.queryParams.versionName = item.version;
                  //   }
                  // });
                  this.queryParams.versionid = this.versionsArr[0].id;
                  this.queryParams.versionName = this.versionsArr[0].version;
                  console.log(this.queryParams, "查询参数变成新增的");
                  resolve(true);
                } else {
                  // 修改
                  console.log(this.queryParams, "查询参数不变");
                  resolve(true);
                }
              }
            }
          })
          .catch((error) => {
            // this.$message.error("系统错误,请联系管理员!20014");
          });
      });
    },
    // 下拉请求政策文件集合
    handleSelectfile(falge) {
      if (falge) {
        this.requestPlatelist();
      }
    },
    // todo 获取政策文件集合
    requestPlatelist() {
      getPlatelist("1")
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, 123123);
          this.officialFileArr = res?.data ?? [];
        })
        .catch((error) => {
          // this.$message.error("系统错误,请联系管理员!300804");
        });
    },
    //! 搜索按钮
    handleQuery(aa) {
      if (aa) {
        this.getList();
      } else if (aa == 0) {
        if (
          this.queryParams.versionid !== "" &&
          this.queryParams.versionid !== null
        ) {
          // 搜索请求
          this.getList();
        } else {
          this.$message.warning("搜索必须先确定版本号");
        }
      }
    },
    //! 重置按钮
    handleresetQuery() {
      this.resetQuery();
      this.initializeGet();
    },
    //? 重置搜索表单
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        type: null,
        versionid: null,
        versionName: null,
      };
    },
    //? 重置新增表单
    resetAdd() {
      this.resetForm("addform");
    },
    //? 清空表格
    restTable() {
      this.listform.list = [];
    },
    //? 条件搜索框和输入框可否输入重置
    changeFlage(status) {
      this.inputFlage = status;
      this.showSearch = status;
    },
    //* 编辑按钮
    handleEdit() {
      // 首先判断版本号有无
      if (this.queryParams.versionid !== null) {
        if (this.editFlage) {
          // 编辑时打开编辑权限 按钮变保存
          this.editFlage = !this.editFlage;
          this.handleSelectver();
          this.changeFlage(false);
        } else {
          this.$refs["addform"].validate((valid) => {
            if (valid) {
              this.$refs["tableForm"].validate((throu) => {
                if (throu) {
                  if (this.listform.list.length == 0) {
                    this.$message.error("电价版本最起码需要一条配置");
                  } else {
                    const ff = this.validNorepeat(this.listform.list);
                    if (ff) {
                      this.$confirm("确认修改该版本吗?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                      })
                        .then(() => {
                          this.requestEdit();
                        })
                        .catch(() => {
                          this.$message({
                            type: "info",
                            message: "已取消",
                          });
                        });
                    }
                  }
                }
              });
            }
          });
        }
      } else {
        this.$message.warning("编辑必须先确定版本号");
      }
    },
    // todo 请求编辑接口
    requestEdit() {
      let params = {};
      params = this.requestParamsDeal(params);
      // debugger;
      editPricemanage(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          // 保存时 请求接口发送修改以后的数据 成功后改变editFlage
          this.editFlage = true;
          this.changeFlage(true);
          // 重新请求版本号的集合(根据ID请求修改后的该版本)
          this.initializeGet(this.queryParams.versionid);
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20010");
        });
    },
    //* 新增按钮
    handleAdd() {
      if (this.addFlage) {
        // 新增版本时打开新增权限 清空查询条件 清空表格所有数据并打开新增表格行数的按钮
        this.resetQuery();
        this.resetAdd();
        this.restTable();
        // 默认添加一行 数据结构等接口
        this.listform.list.push(deepClone(this.rowObj));
        this.addFlage = !this.addFlage;
        this.changeFlage(false);
      } else {
        // 确认新增
        this.$refs["queryForm"].validate((tigger) => {
          // 通过版本号校验
          if (tigger) {
            this.$refs["addform"].validate((valid) => {
              // 通过addform校验
              if (valid) {
                if (this.listform.list.length == 0) {
                  this.$message.error("电价版本最起码需要一条配置");
                } else {
                  const ff = this.validNorepeat(this.listform.list); // 表格数据重复校验
                  if (ff) {
                    this.$refs["tableForm"].validate((throu) => {
                      // 通过tableForm校验
                      if (throu) {
                        this.$confirm("确认添加该版本吗?", "提示", {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning",
                        })
                          .then(() => {
                            this.requestAdd();
                          })
                          .catch(() => {
                            this.$message({
                              type: "info",
                              message: "已取消",
                            });
                          });
                      }
                    });
                  }
                }
              }
            });
          }
        });
      }
    },
    // todo 请求新增接口
    requestAdd() {
      let params = {};
      params = this.requestParamsDeal(params);
      // debugger;
      addPricemanage(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.addFlage = true;
          this.changeFlage(true);
          // 重新请求版本号的集合(根据ID请求新增后的该版本)
          // this.addVersionname = null;
          // this.addVersionname = Number(this.queryParams.versionName);
          this.initializeGet("add");
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20011");
        });
    },
    //! 新增或编辑参数处理
    requestParamsDeal(params) {
      params.makingUserId = this.$store.state.user.id;
      if (!this.addFlage) {
        params.id = null;
      }
      if (!this.editFlage) {
        params.id = this.queryParams.versionid;
      }
      params.version = this.queryParams.versionName;
      params.website = this.addParams.website;
      params.servicePhone = this.addParams.servicePhone;
      // params.officialFile = this.addParams.officialFile;
      params.officialFileId = this.addParams.officialFileId;
      params.energyPriceDetailVoList = this.listform.list;
      console.log(params, "请求参数");
      return params;
    },
    // * 取消新增或编辑按钮
    handleCancel() {
      this.resetAdd();
      this.restTable();
      this.changeFlage(true);
      // 新增时候取消重新获取版本号默认渲染第一个
      if (!this.addFlage) {
        this.resetQuery();
        this.addFlage = true;
        this.initializeGet();
      }
      // 修改的时候渲染当前的版本号
      if (!this.editFlage) {
        this.editFlage = true;
        // 重新请求版本号的集合(根据ID请求修改后的该版本)
        this.initializeGet(this.queryParams.versionid);
      }
    },
    //* 发布按钮
    handlePublish() {
      this.$confirm("确认发布该版本吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.publishRequest();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //todo 发布请求
    publishRequest() {
      let params = {};
      params.id = this.queryParams.versionid;
      params.publishUserId = this.$store.state.user.id;
      params.status = 1;
      console.log(params, "发布参数");
      // debugger;
      auditPricemanage(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "发布成功!",
            });
            this.initializeGet(this.queryParams.versionid);
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20013");
        });
    },
    // 表格新增一行
    addRow() {
      // 新增版本时打开新增权限才能新增行
      if (!this.addFlage || !this.editFlage) {
        this.listform.list.push(deepClone(this.rowObj));
      }
    },
    //* 下载预览按钮
    preview() {
      if (
        this.addParams.officialFileId == "" ||
        this.addParams.officialFileId == null
      ) {
        this.$message.warning("缺少文件");
        return false;
      }
      if (this.officialFileArr.length == 0) {
        this.$message.warning("缺少文件集合或者改文件已查询不到");
        return false;
      } else {
        let num = 0;
        this.officialFileArr.map((item) => {
          if (item.id == this.addParams.officialFileId) {
            if (item.filePath && item.filePath != "") {
              window.open(process.env.VUE_APP_BASE_API + "/" + item.filePath);
            } else {
              this.$message.warning("该文件路径已失效");
              return false;
            }
          } else {
            num++;
          }
        });
        if (num == this.officialFileArr.length) {
          this.$message.warning("该文件未找到");
          return false;
        }
      }
    },
    /* ....................表格相关..................... */
    // 删除
    handleDelete(row) {
      const index = this.listform.list.indexOf(row);
      this.listform.list.splice(index, 1);
    },
    // 输入框输入只能是4位小数
    replaceDigitDeal(val, digit, index, key) {
      this.listform.list[index][key] = replaceDigit(val, digit);
    },
    // 峰谷差价计算
    toInteger(val, digit, index, key) {
      this.replaceDigitDeal(val, digit, index, key);
      let diffPrice = 0;
      let peak = this.listform.list[index].peakPrice;
      let low = this.listform.list[index].lowPrice;
      console.log(peak, low);
      if (peak != "" && peak != null && low != "" && low != null) {
        if (peak != 0 && low != 0) {
          if (peak >= low) {
            diffPrice = peak - low;
            this.listform.list[index].diffPrice = replaceDigit(diffPrice, 4);
          } else if (peak < low) {
            diffPrice = null;
            this.listform.list[index].diffPrice = diffPrice;
            this.$message.error("尖峰值请勿小于低峰值");
          } else if (peak == low) {
            this.listform.list[index].diffPrice = 0;
          }
        } else if (peak == 0 || low == 0) {
          if (peak > low) {
            diffPrice = peak - low;
            this.listform.list[index].diffPrice = replaceDigit(diffPrice, 4);
          } else {
            diffPrice = null;
            this.listform.list[index].diffPrice = diffPrice;
            this.$message.error("尖峰值请勿小于低峰值");
          }
        }
      } else {
        diffPrice = null;
        this.listform.list[index].diffPrice = diffPrice;
      }
    },
    // 起始结束值校验对比
    checknum(value, rowindex, key) {
      this.indexFlage = rowindex;
      this.listform.list[rowindex][key] = replaceInteger(value);
    },
    checknum2(value, rowindex, key) {
      this.indexFlage = rowindex;
      this.listform.list[rowindex][key] = replaceInteger(value);
    },
  },
};
</script>

<style scoped lang="scss">
.energyUnitprice {
  .cellCenter {
    margin-top: 20px;
  }
  .midrow {
    background-color: #f2f2f5;
    margin-bottom: 10px;
  }
  .midcol {
    height: 60px;
    position: relative;
    .el-form-item {
      margin: 9px 0 0 20px;
    }
    .sapn-input {
      width: 250px;
      /*1. 先强制一行内显示文本*/
      white-space: nowrap;
      /*2. 超出的部分隐藏*/
      overflow: hidden;
      /*3. 文字用省略号替代超出的部分*/
      text-overflow: ellipsis;
    }
  }
  .inline-col {
    display: flex;
    flex-wrap: nowrap;
    ::v-deep .el-form-item__content {
      width: 400px;
    }
    .el-button {
      margin-bottom: 10px;
    }
  }
  .midcolmini {
    height: 42px;
    .el-button {
      margin-bottom: -5px;
    }
  }
  .preview-button {
    float: left;
  }
  .midbutton {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  // .show-tooltip {
  // }
  // ::v-deep .el-tooltip__popper.is-light {
  //   border: 2px solid #fff;
  // }
}
.flexex {
  display: flex;
  // justify-content: space-between;
  justify-content: center;
  align-items: center;
  // padding: 0 20px;
  .el-icon-info {
    font-size: 18px;
    cursor: pointer;
    margin-left: 10px;
  }
}
.button-area-ex {
  margin-top: 2px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.versionName-span {
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #3669d4;
  line-height: 22px;
}
.versionName-span2 {
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #f8d400;
  line-height: 22px;
}
</style>
